<template>
  <div>
    <el-input
      v-model="keyword"
      placeholder="搜索商品"
      style="width: 200px; margin-bottom: 16px;"
    />
    <el-button
      type="primary"
      @click="openDialog()"
    >
      新增商品
    </el-button>
    <el-table
      :data="pagedData"
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column
        prop="name"
        label="商品名"
      />
      <el-table-column
        prop="price"
        label="价格"
      />
      <el-table-column
        prop="image"
        label="图片"
      >
        <template #default="scope">
          <img
            :src="scope.row.image"
            style="width:40px;height:40px;object-fit:cover;"
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="small"
            @click="openDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="onDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      style="margin-top: 16px; text-align: right;"
      background
      layout="prev, pager, next"
      :total="filteredData.length"
      :page-size="pageSize"
    />
    <el-dialog
      v-model="dialogVisible"
      :title="editRow ? '编辑商品' : '新增商品'"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="商品名"
          prop="name"
        >
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item
          label="价格"
          prop="price"
        >
          <el-input
            v-model="form.price"
            type="number"
          />
        </el-form-item>
        <el-form-item
          label="图片"
          prop="image"
        >
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleUpload"
            :before-upload="beforeUpload"
            action="#"
            :http-request="dummyUpload"
          >
            <img
              v-if="form.image"
              :src="form.image"
              class="avatar"
            >
            <el-icon v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="onSave"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const keyword = ref('')
const pageSize = 5
const currentPage = ref(1)
const dialogVisible = ref(false)
const editRow = ref<any>(null)
const formRef = ref()
const form = ref({ name: '', price: '', image: '' })
const rules = {
  name: [{ required: true, message: '请输入商品名', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'change' }]
}
const tableData = ref([
  { name: '二手书', price: 10, image: 'https://img2.imgtp.com/2024/05/01/1.jpg' },
  { name: '二手自行车', price: 200, image: 'https://img2.imgtp.com/2024/05/01/2.jpg' },
  { name: '二手台灯', price: 30, image: 'https://img2.imgtp.com/2024/05/01/3.jpg' },
  { name: '二手耳机', price: 50, image: 'https://img2.imgtp.com/2024/05/01/4.jpg' }
])
const filteredData = computed(() =>
  tableData.value.filter(item => item.name.includes(keyword.value))
)
const pagedData = computed(() =>
  filteredData.value.slice((currentPage.value - 1) * pageSize, currentPage.value * pageSize)
)
function openDialog(row?: any) {
  dialogVisible.value = true
  if (row) {
    editRow.value = row
    form.value = { ...row }
  } else {
    editRow.value = null
    form.value = { name: '', price: '', image: '' }
  }
}
function onSave() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return
    if (editRow.value) {
      Object.assign(editRow.value, form.value)
      ElMessage.success('编辑成功')
    } else {
      tableData.value.push({ ...form.value })
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
  })
}
function onDelete(row: any) {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', { type: 'warning' })
    .then(() => {
      tableData.value = tableData.value.filter(item => item !== row)
      ElMessage.success('删除成功')
    })
}
function handleUpload(res: any, file: any) {
  // 这里用本地base64模拟图片上传
  const reader = new FileReader()
  reader.onload = e => {
    form.value.image = e.target?.result as string
  }
  reader.readAsDataURL(file.raw)
}
function beforeUpload(file: File) {
  const isJPG = file.type.startsWith('image/')
  if (!isJPG) {
    ElMessage.error('只能上传图片文件')
  }
  return isJPG
}
function dummyUpload(param: any) {
  // 模拟上传，直接回调onSuccess
  setTimeout(() => param.onSuccess({}, param.file), 500)
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 6px;
  object-fit: cover;
}
</style> 